import http from 'k6/http';
import { check, sleep } from 'k6';
import { Rate } from 'k6/metrics';

// 自定义指标
const errorRate = new Rate('errors');
const responseTime = new Rate('response_time');

// 测试配置
export const options = {
  stages: [
    { duration: '2m', target: 10 }, // 预热阶段
    { duration: '5m', target: 50 }, // 正常负载
    { duration: '3m', target: 100 }, // 峰值负载
    { duration: '5m', target: 200 }, // 高负载
    { duration: '2m', target: 50 },  // 恢复阶段
    { duration: '2m', target: 10 }, // 冷却阶段
  ],
  thresholds: {
    http_req_duration: ['p(95)<2000'], // 95%的请求在2秒内完成
    http_req_failed: ['rate<0.1'], // 错误率低于10%
    errors: ['rate<0.1'], // 自定义错误率低于10%
    response_time: ['p(95)<1500'], // 95%的响应时间在1.5秒内
  },
};

// 环境配置
const BASE_URL = __ENV.BASE_URL || 'http://localhost:5000';
const API_TOKEN = __ENV.API_TOKEN || '';

export default function () {
  // 设置请求头
  const params = {
    headers: {
      'Authorization': `Bearer ${API_TOKEN}`,
      'Content-Type': 'application/json',
      'User-Agent': 'MatrixFramework-LoadTest/1.0',
    },
  };

  // 租户管理服务测试
  const tenantManagementTests = {
    // 获取租户列表
    getTenants: {
      executor: 'ramping-vus',
      stages: [
        { duration: '30s', target: 5 },
        { duration: '1m', target: 20 },
        { duration: '30s', target: 5 },
      ],
      exec: function() {
        const response = http.get(`${BASE_URL}/api/tenant-management/tenants?skipCount=0&maxResultCount=20`, params);

        check(response, {
          '获取租户列表成功': (r) => r.status === 200,
          '响应格式正确': (r) => r.headers['Content-Type'] && r.headers['Content-Type'].includes('application/json'),
          '返回数据不为空': (r) => r.json('items').length > 0,
        });

        responseTime.add(response.timings.duration);
      },
    },

    // 创建租户
    createTenant: {
      executor: 'ramping-vus',
      stages: [
        { duration: '30s', target: 2 },
        { duration: '1m', target: 10 },
        { duration: '30s', target: 2 },
      ],
      exec: function() {
        const tenantData = {
          name: `Test Tenant ${Math.random().toString(36).substr(2, 9)}`,
          code: `test-${Math.random().toString(36).substr(2, 6)}`,
          displayName: `Display Name ${Math.random().toString(36).substr(2, 8)}`,
          description: 'Load test tenant',
          config: {
            features: {
              user_management: true,
              file_storage: true,
              api_access: true,
            },
            security: {
              requireTwoFactorAuth: false,
              allowPasswordChange: true,
              sessionTimeoutMinutes: 30,
            }
          },
          quota: {
            users: {
              maxUsers: 100,
              maxAdmins: 10,
            },
            storage: {
              maxStorageMB: 1024,
            },
            api: {
              maxCallsPerDay: 10000,
              maxCallsPerHour: 1000,
              maxCallsPerMinute: 100,
            }
          }
        };

        const response = http.post(`${BASE_URL}/api/tenant-management/tenants`, JSON.stringify(tenantData), params);

        check(response, {
          '创建租户成功': (r) => r.status === 201,
          '返回租户ID': (r) => r.json('id') !== undefined,
          '租户名称匹配': (r) => r.json('name') === tenantData.name,
        });

        // 存储创建的租户ID用于后续测试
        if (response.status === 201) {
          __ENV.CREATED_TENANT_ID = response.json('id');
        }

        responseTime.add(response.timings.duration);
      },
    },

    // 获取租户详情
    getTenantDetails: {
      executor: 'constant-vus',
      vus: 10,
      duration: '2m',
      exec: function() {
        // 使用预定义的租户ID或创建新租户
        let tenantId = __ENV.CREATED_TENANT_ID;
        if (!tenantId) {
          // 创建测试租户
          const createResponse = http.post(`${BASE_URL}/api/tenant-management/tenants`, JSON.stringify({
            name: 'Performance Test Tenant',
            code: 'perf-test',
            displayName: 'Performance Test',
            description: 'Tenant for performance testing',
          }), params);

          if (createResponse.status === 201) {
            tenantId = createResponse.json('id');
          }
        }

        if (!tenantId) {
          return; // 跳过测试
        }

        const response = http.get(`${BASE_URL}/api/tenant-management/tenants/${tenantId}`, params);

        check(response, {
          '获取租户详情成功': (r) => r.status === 200,
          '租户信息完整': (r) => r.json('id') === tenantId,
          '配额信息存在': (r) => r.json('quota') !== undefined,
        });

        responseTime.add(response.timings.duration);
      },
    },

    // 更新租户
    updateTenant: {
      executor: 'ramping-vus',
      stages: [
        { duration: '30s', target: 3 },
        { duration: '1m', target: 15 },
        { duration: '30s', target: 3 },
      ],
      exec: function() {
        const tenantId = __ENV.CREATED_TENANT_ID;
        if (!tenantId) return;

        const updateData = {
          name: `Updated Tenant ${Math.random().toString(36).substr(2, 6)}`,
          displayName: `Updated Display ${Math.random().toString(36).substr(2, 7)}`,
          description: 'Updated for performance test',
        };

        const response = http.put(`${BASE_URL}/api/tenant-management/tenants/${tenantId}`, JSON.stringify(updateData), params);

        check(response, {
          '更新租户成功': (r) => r.status === 200,
          '名称已更新': (r) => r.json('name').includes('Updated'),
        });

        responseTime.add(response.timings.duration);
      },
    },

    // 租户状态管理
    tenantLifecycle: {
      executor: 'per-vus-iterations',
      vus: 5,
      iterations: 10,
      duration: '3m',
      exec: function() {
        const tenantId = __ENV.CREATED_TENANT_ID;
        if (!tenantId) return;

        const operations = ['activate', 'suspend', 'activate'];
        const operation = operations[Math.floor(Math.random() * operations.length)];

        const response = http.post(`${BASE_URL}/api/tenant-management/tenants/${tenantId}/${operation}`, '', params);

        check(response, {
          '状态操作成功': (r) => r.status === 200 || r.status === 204,
        });

        if (response.status >= 400) {
          errorRate.add(1);
        }

        sleep(1);
      },
    },
  };

  // 用户系统服务测试
  const userSystemTests = {
    // 获取用户列表
    getUsers: {
      executor: 'ramping-vus',
      stages: [
        { duration: '30s', target: 10 },
        { duration: '1m', target: 30 },
        { duration: '30s', target: 10 },
      ],
      exec: function() {
        const response = http.get(`${BASE_URL}/api/user-system/users?skipCount=0&maxResultCount=20`, params);

        check(response, {
          '获取用户列表成功': (r) => r.status === 200,
          '响应格式正确': (r) => r.headers['Content-Type'] && r.headers['Content-Type'].includes('application/json'),
        });

        responseTime.add(response.timings.duration);
      },
    },

    // 用户认证测试
    userAuthentication: {
      executor: 'constant-vus',
      vus: 20,
      duration: '3m',
      exec: function() {
        const loginData = {
          username: `testuser${Math.floor(Math.random() * 1000)}@matrix.com`,
          password: 'TestPassword123!',
          rememberMe: false,
        };

        const response = http.post(`${BASE_URL}/api/user-system/auth/login`, JSON.stringify(loginData), params);

        check(response, {
          '用户登录成功': (r) => r.status === 200,
          '返回访问令牌': (r) => r.json('accessToken') !== undefined,
          '返回用户信息': (r) => r.json('user') !== undefined,
        });

        if (response.status >= 400) {
          errorRate.add(1);
        }

        // 测试令牌验证
        if (response.status === 200 && response.json('accessToken')) {
          const token = response.json('accessToken');
          const tokenResponse = http.get(`${BASE_URL}/api/user-system/auth/verify`, {
            headers: {
              ...params.headers,
              'Authorization': `Bearer ${token}`,
            },
          });

          check(tokenResponse, {
            '令牌验证成功': (r) => r.status === 200,
          });
        }

        responseTime.add(response.timings.duration);
      },
    },
  };

  // 相册管理服务测试
  const photoAlbumTests = {
    // 获取相册列表
    getAlbums: {
      executor: 'ramping-vus',
      stages: [
        { duration: '30s', target: 5 },
        { duration: '1m', target: 25 },
        { duration: '30s', target: 5 },
      ],
      exec: function() {
        const response = http.get(`${BASE_URL}/api/photo-album/albums?skipCount=0&maxResultCount=20`, params);

        check(response, {
          '获取相册列表成功': (r) => r.status === 200,
          '响应格式正确': (r) => r.headers['Content-Type'] && r.headers['Content-Type'].includes('application/json'),
        });

        responseTime.add(response.timings.duration);
      },
    },

    // 文件上传测试
    fileUpload: {
      executor: 'constant-vus',
      vus: 5,
      duration: '2m',
      exec: function() {
        // 生成测试文件
        const fileContent = new Array(1024).fill('A').join(''); // 1KB 文件
        const fileName = `test-file-${Math.random().toString(36).substr(2, 9)}.txt`;

        const formData = {
          file: http.file(fileContent, fileName, 'text/plain'),
          albumId: 'test-album',
          description: 'Load test file',
        };

        const response = http.post(`${BASE_URL}/api/photo-album/photos/upload`, formData, {
          headers: {
            ...params.headers,
            'Content-Type': 'multipart/form-data',
          },
        });

        check(response, {
          '文件上传成功': (r) => r.status === 201,
          '返回文件信息': (r) => r.json('id') !== undefined,
        });

        if (response.status >= 400) {
          errorRate.add(1);
        }

        responseTime.add(response.timings.duration);
      },
    },
  };

  // 系统健康检查
  const healthChecks = {
    systemHealth: {
      executor: 'constant-vus',
      vus: 5,
      duration: '10m',
      exec: function() {
        // API网关健康检查
        const gatewayHealth = http.get(`${BASE_URL}/healthz`, {
          timeout: '5s',
        });

        check(gatewayHealth, {
          'API网关健康': (r) => r.status === 200,
        });

        // 服务注册中心健康检查
        const registryHealth = http.get(`${BASE_URL}/api/registry/health`, {
          timeout: '5s',
        });

        check(registryHealth, {
          '服务注册中心健康': (r) => r.status === 200,
        });

        // 数据库健康检查
        const dbHealth = http.get(`${BASE_URL}/api/health/database`, {
          timeout: '10s',
        });

        check(dbHealth, {
          '数据库连接正常': (r) => r.status === 200,
        });

        // Redis健康检查
        const redisHealth = http.get(`${BASE_URL}/api/health/redis`, {
          timeout: '5s',
        });

        check(redisHealth, {
          'Redis连接正常': (r) => r.status === 200,
        });

        sleep(10);
      },
    },
  };

  // 主测试场景
  export default function () {
    // 初始化
    console.log('Matrix Framework Load Test Started');
    console.log(`Base URL: ${BASE_URL}`);
    console.log(`Environment: ${__ENV.ENVIRONMENT || 'test'}`);

    // 预热阶段
    console.log('Warming up...');
    sleep(10);

    // 执行测试组合
    const testGroups = [
      { name: 'Health Checks', tests: healthChecks },
      { name: 'Tenant Management', tests: tenantManagementTests },
      { name: 'User System', tests: userSystemTests },
      { name: 'Photo Album', tests: photoAlbumTests },
    ];

    // 随机化测试顺序
    for (const group of testGroups.sort(() => Math.random() - 0.5)) {
      console.log(`Running ${group.name} tests...`);

      // 运行测试组中的所有测试
      Object.values(group.tests).forEach(test => {
        if (typeof test === 'function') {
          test();
        }
      });
    }

    // 清理阶段
    console.log('Cleaning up test data...');

    // 删除测试租户
    if (__ENV.CREATED_TENANT_ID) {
      http.del(`${BASE_URL}/api/tenant-management/tenants/${__ENV.CREATED_TENANT_ID}`, params);
    }

    console.log('Load Test Completed');
  }
}

// 导出配置
export { errorRate, responseTime };